package com.tony.pmp.server.service.impl;

import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
import com.tony.pmp.common.utils.CommonUtil;
import com.tony.pmp.common.utils.Constant;
import com.tony.pmp.model.entity.SysUserEntity;
import com.tony.pmp.model.mapper.SysDeptMapper;
import com.tony.pmp.model.mapper.SysUserMapper;
import com.tony.pmp.server.service.CommonDataService;
import com.tony.pmp.server.service.SysDeptService;
import com.tony.pmp.server.shiro.ShiroUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * Created with IntelliJ IDEA.
 *
 * @Title: CommonDataServiceImpl
 * @Auther: 皮蛋布丁
 * @Date: 2021/07/29/14:32
 * @Description: 通用部门权限控制接口的是实现
 */
@Service("commonDataService")
public class CommonDataServiceImpl implements CommonDataService {

    private static final Logger log = LoggerFactory.getLogger(CommonDataServiceImpl.class);

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysDeptService sysDeptService;

    /**
    * @Description: getCurrUserDataDeptIdsStr 将部门数据id列表转化为id拼接的字符串
    * @Param: []
    * @return: java.lang.String
    * @Author: 皮蛋布丁
    * @Date: 2021/7/29 14:39
    */
    @Override
    public String getCurrUserDataDeptIdsStr() {
        String result = null;
        //获取当前登录用户的部门数据id列表
        Set<Long> dataSet = this.getCurrUserDataDeptIds();
        if (dataSet != null && !dataSet.isEmpty()) {
            result = CommonUtil.concatStrToInt(Joiner.on(",").join(dataSet),",");
        }
        return result;
    }

    /**
     * @Description: getCurrUserDataDeptIds 获取当前登录用户的部门数据id列表
     * @Param: []
     * @return: java.util.Set<java.lang.Long>
     * @Author: 皮蛋布丁
     * @Date: 2021/7/29 14:35
     */
    @Override
    public Set<Long> getCurrUserDataDeptIds() {
        Set<Long> dataIds = Sets.newHashSet();
        //获取登录用户
        SysUserEntity userEntity = ShiroUtil.getUserEntity();
        if (Constant.SUPER_ADMIN == userEntity.getUserId()) {
            //获取所有部门id列表
            dataIds = sysDeptMapper.queryAllDeptIds();
        } else {
            //分配给用户的部门数据权限id列表
            Set<Long> userDeptDataIds = sysUserMapper.queryDeptIdsByUserId(userEntity.getUserId());
            if (userDeptDataIds != null && !userDeptDataIds.isEmpty()) {
                dataIds.addAll(userDeptDataIds);
            }
            //获取用户所在的部门及其子部门id列表(递归)
            dataIds.add(userEntity.getDeptId());
            List<Long> subDeptIdList = sysDeptService.getSubDeptIdList(userEntity.getDeptId());
            dataIds.addAll(Sets.newHashSet(subDeptIdList));

        }
        return dataIds;
    }
}
